<template>
	<div class="app-container">
		<div class="wx-user-box">
			<div class="wx-user-title">分账模板</div>
			<div class="search-box">
				<!-- 查询 -->
				<el-form :inline="true" class="demo-form-inline">
					<el-form-item label="模板名称">
						<el-input v-model="name" placeholder="请输入模板名称查询" clearable @change="sousuo()" style="width: 300px;"></el-input>
					</el-form-item>

					<el-form-item><el-button type="primary" @click="sousuo()" icon="el-icon-search">查询</el-button></el-form-item>
					<el-form-item><el-button type="primary" @click="add()" icon="el-icon-circle-plus-outline">添加模板</el-button></el-form-item>
				</el-form>

				<el-table border :data="list" style="width: 100%">
					<el-table-column prop="name" label="分账名称"></el-table-column>
					<el-table-column prop="device_count" label="关联站点数量"></el-table-column>
					<el-table-column prop="createtime" label="创建时间"></el-table-column>

					<el-table-column label="操作">
						<template slot-scope="scope">
							<el-button size="mini" @click="add_edit(scope.row.id)">编辑</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<!-- 分页 -->
			<div class="wx-user-pagination-div">
				<el-pagination
					background
					:current-page="currentPage"
					:page-sizes="pageSizes"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
					:pager-count="pageCount"
					prev-text="上一页"
					next-text="下一页"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</div>

		<el-dialog :title="form.id ? '修改分账模板' : '添加分账模板'" :visible.sync="dialogVisible" width="850px">
			<el-form ref="form" :model="form" label-width="120px" class="form">
				<el-form-item label="模板名称"><el-input style="width: 200px;" placeholder="请输入模板名称" v-model="form.name"></el-input></el-form-item>
				<el-form-item label="代理商" v-if="!isAgent">
					<el-select v-model="form.agent_id" placeholder="请选择代理商" @change="selAgentBuckle(form.agent_id)">
						<el-option v-for="(item,index) in agentList" :key="index" :label="item.name" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="代理商扣点" ><el-input readonly style="width: 200px;" v-model="form.agent_buckle" placeholder="请输入代理商扣点"></el-input><span>（%）</span> </el-form-item>
				<el-form-item label="平台扣点"><el-input type="number" style="width: 200px;" v-model="form.platform_buckle" placeholder="请输入平台扣点"></el-input><span>（%）</span> </el-form-item>
				<div v-for="(template,index) in form.template_item" :key="index">
					<el-form-item :label="'分账人员 ('+(index + 1)+')'">
						<el-select v-model="template.share_user_id" placeholder="请选择分账人员">
							<el-option v-for="(item,index) in wuyeList" :key="index" :label="item.name" :value="item.id"></el-option>
						</el-select>
						<span class="title">分账比例</span><el-input type="number" v-model="template.share_proportion" style="width: 200px;" placeholder="请输入分账比例"></el-input><span>（%）</span> 
						<el-button type="warning" v-if="index == (form.template_item.length - 1)" icon="el-icon-plus" @click="addTemplateItem()" size="mini" circle></el-button>
						<el-button type="danger" v-if="index == (form.template_item.length - 1) && form.template_item.length > 1" icon="el-icon-delete" @click="delTemplateItem()" size="mini" circle></el-button>
					</el-form-item>
				</div>
				
			</el-form>
			<span slot="footer" class="dialog-footer">
				<span style="margin-right: 30px;color: #999999;">总分账比例：{{sum}}%</span>
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="save()">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import { query, add_edit, save, selAgentBuckle, agentQuery, wuye_query } from '@/api/sub-account';
export default {
	name: 'sub-account',
	data() {
		return {
			pageSize: 10, // 每页条数
			pageCount: 7, //
			pageSizes: [10, 20, 30, 40, 50, 100], // 个数选择器
			currentPage: 1, // 当前页码
			total: 0, // 总条数
			list: [],
			setItem: {},
			name: '',
			form: {
				id:'',
				name: '',
				agent_id:'',
				agent_buckle:'',
				platform_buckle:'',
				template_item:[{share_user_id:'',share_proportion:''}]
			},
			dialogVisible: false,
			agentList:[],
			wuyeList:[],
			isAgent:false //false表示是总后台在添加分账模板，true标识是代理商在添加 <boolean>
		};
	},
	 computed: {
		sum() {
			let sum = 0
			sum += +this.form.agent_buckle;
			sum += +this.form.platform_buckle;
			this.form.template_item.forEach(item => {
				sum += +item.share_proportion
			})
			
			return sum
		},
		userinfo() {
			return this.$store.state.user.userinfo
		}
	},

	created() {
		this.getData();
		this.add_edit()
	},
	methods: {
		addTemplateItem(){
			this.form.template_item.push({share_user_id:'',share_proportion:''})
		},
		delTemplateItem(){
			this.form.template_item.splice(this.form.template_item.length - 1 ,1)
		},
	
 		getData() {
			let data = {
				pageNumber: this.currentPage,
				pageSize: this.pageSize
			};
			if (this.name) {
				data['name'] = this.name;
			}
			query(data).then(res => {
				if (res.state) {
					this.total = res.data.totalRow;
					this.list = res.data.list;
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		//获取代理商扣点
		selAgentBuckle(agent_id) {
			selAgentBuckle({
				agent_id:agent_id
			}).then(res => {
				if (res.state) {
					this.form.agent_buckle = res.data 
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		// 修改回填
		add_edit(tmp_id) {
			add_edit({
				tmp_id: tmp_id
			}).then(res => {
				if (res.state) {
					this.wuyeList = res.data.userList
					this.isAgent = res.data.is_agent
					this.agentList = res.data.agentList
					if(tmp_id) {
						this.form = res.data.template
						this.dialogVisible = true
					}else{
						if(this.isAgent) {
							this.form.agent_id = this.userinfo.agent_id
							this.selAgentBuckle(this.userinfo.agent_id)
						}
					}
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		// 添加修改
		save(tmp_id) {
			if(!this.form.name) {
				this.$message.error('请输入模板名称！');
				return
			}
			if(!this.form.agent_id) {
				this.$message.error('请选择代理商！');
				return
			}
			if(!this.form.agent_buckle) {
				this.$message.error('请输入代理商扣点！');
				return
			}
			if(!this.form.platform_buckle) {
				this.$message.error('请输入平台扣点！');
				return
			}
			
			let idList = []
			let is = true
			let sum = (+this.form.agent_buckle) + (+this.form.platform_buckle)
			for (let i=0;i<this.form.template_item.length;i++) {
				sum += (+this.form.template_item[i].share_proportion)
				idList.push(this.form.template_item[i].share_user_id)
				if(!this.form.template_item[i].share_user_id) {
					this.$message.error('分账人员不能为空！');
					is = false
					break;
				}else if(!this.form.template_item[i].share_proportion) {
					this.$message.error('分账比例不能为空！');
					is = false
					break;
				}
			}
			if(!is) {
				return
			}
			
			if(this.isArrRepeat(idList)) {
				this.$message.error('分账人员不能重复！');
				return
			}
			
			if(sum != 100) {
				this.$message.error('总分值比例不等于100%，请重新分配！');
				return
			}
			
			
			
			let data = {}
			if(this.form.id) {
				data['template.id'] = this.form.id
			}
			data['template.name'] = this.form.name
			data['template.agent_id'] = this.form.agent_id
			data['template.agent_buckle'] = this.form.agent_buckle
			data['template.platform_buckle'] = this.form.platform_buckle
			data['template_item'] = JSON.stringify(this.form.template_item) 
			save(data).then(res => {
				if (res.state) {
					if(!this.form.id) {
						this.currentPage = 1;
					}
					this.getData()
					this.$message({
					  message: '提交成功',
					  type: 'success'
					});
					this.dialogVisible = false
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		
		// 判断数组是否有重复元素
		isArrRepeat(_arr){
		    let is_repeat=false;
		    _arr.map((item,index)=>{
		        if(_arr.indexOf(item)!=index){
		            is_repeat=true;
		        }
		    });
		    return is_repeat;
		},
		
		add() {
			this.form = {
				id:'',
				name: '',
				agent_id:'',
				agent_buckle:'',
				platform_buckle:'',
				template_item:[{share_user_id:'',share_proportion:''}]
			}
			if(this.isAgent) {
				this.form.agent_id = this.userinfo.agent_id
				this.selAgentBuckle(this.userinfo.agent_id)
			}
			this.dialogVisible = true
		},

		sousuo(e) {
			this.currentPage = 1;
			this.getData();
		},
		// 每页显示的条数
		handleSizeChange(val) {
			this.pageSize = val;
			this.getData(1, val);
			// 注意：在改变每页显示的条数时，要将页码显示到第一页
			this.currentPage = 1;
		},

		// 显示第几页
		handleCurrentChange(val) {
			this.currentPage = val;
			// 切换页码时，要获取每页显示的条数
			this.getData(val, this.pageSize);
		}
	}
};
</script>
<style lang="scss" scoped>
.form {
	.title{
		line-height: 36px;
		font-size: 14px;
		color: #606266;
		font-weight: 700;
		margin: 12px;
	}
}
</style>
